//
//  ZAdvertisementViewController.m
//  DoctorFAQs
//
//  Created by zjq on 17/3/14.
//  Copyright © 2017年 zjq. All rights reserved.
//

#import "ZAdvertisementViewController.h"
#import "SDCycleScrollView.h"
@interface ZAdvertisementViewController ()<SDCycleScrollViewDelegate>
@property (nonatomic,strong) SDCycleScrollView * cycleScrollView;
@property (nonatomic,strong) UIButton  * countdownBtn;// 进入app的button
@property (nonatomic,strong) UIButton * timingBtn;// 计时的按钮
@property (nonatomic,strong) UIImageView * imageView; // 背景图;
@property (nonatomic,strong) NSMutableArray * imgArray;
@property (nonatomic,copy) dispatch_source_t timer;
@end

@implementation ZAdvertisementViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initlizeInterface];
    [self adVerNetWorking];
    
}
- (void)initlizeInterface {
    _imgArray = [@[] mutableCopy];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.imageView];
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    [self.view addSubview:self.timingBtn];
    [self.timingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-20*xsIZE);
        make.width.offset(80*xsIZE);
        make.height.offset(20*ysIZE);
        make.top.equalTo(self.view).offset(30*ysIZE);
    }];
    [self leaveTime];
    
}
// 倒计时按钮的方法
- (void)timeingButtonAction {
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
        [self.view addSubview:self.cycleScrollView];
        [self.cycleScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        _timer = nil;
        [self.view addSubview:self.countdownBtn];
        [self.countdownBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.height.offset(45*ysIZE);
            make.width.offset(120*xsIZE);
            make.bottom.equalTo(self.view).offset(-50*ysIZE);
        }];
        [self leadNetWorking];
    }else{

        [self jionZTabbar];

    }
}

// 进入tabbar
- (void)jionZTabbar {
    if (self.adDelegate && [self.adDelegate conformsToProtocol:@protocol(advertisementDelegate)]) {
        _timer = nil;
        [self.adDelegate skipAdvertisement];
    }
}

- (void)leaveTime {
    __block int timeout = 5;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (timeout <= 0) {
            // 倒计时完成
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.countdownBtn.hidden = YES;
                [self.timingBtn setTitle:@"跳转" forState:UIControlStateNormal];
                [self timeingButtonAction];
            });
           
            
        }else {
            int seconds = timeout % 60;
            NSString * strTime = [NSString stringWithFormat:@"%ds 关闭",seconds];
              dispatch_async(dispatch_get_main_queue(), ^{
                  [UIView beginAnimations:nil context:nil];
                  [UIView setAnimationDuration:1];
                  [self.timingBtn setTitle:strTime forState:UIControlStateNormal];
                  
                  [UIView commitAnimations];
              });
            timeout--;

        }
    });
    dispatch_resume(_timer);
}
// 启动页网络请求
- (void)adVerNetWorking {
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:nil paramarsSite:@"Login/start" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 1) {
            [self hanldDataWith:dict];
        }else {
            
        }
    } failure:^(NSError *error) {
        [YJProgressHUD showMessage:@"网络请求错误" inView:self.view];
    }];
}
// 引导页网络请求
- (void)leadNetWorking {
    [BaseRequest requestWithMethodResponseJsonByGet:TestURL paramars:nil paramarsSite:@"Login/lead" sucessBlock:^(id content) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:nil];
        if ([dict[@"code"] intValue] == 1) {
            [self hanldLeadDataWith:dict[@"list"]];
        }else {
            
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)hanldDataWith:(NSDictionary * )imgaedict {
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IconURL,imgaedict[@"img"]]]];
}
- (void)hanldLeadDataWith:(NSMutableArray *)imageArray {
    [_imgArray removeAllObjects];
    for (NSDictionary * dict  in imageArray) {
        NSString * imgUrl = dict[@"img"];
        [_imgArray addObject:[NSString stringWithFormat:@"%@%@",IconURL,imgUrl]];
    }
    self.cycleScrollView.imageURLStringsGroup = _imgArray;
}
// 图片滚动回调
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index {
    self.countdownBtn.hidden = index== _imgArray.count-1 ? NO:YES;
}
- (SDCycleScrollView *)cycleScrollView {
    if (_cycleScrollView) {
        return _cycleScrollView;
    }
    
    _cycleScrollView = [[SDCycleScrollView alloc]init];
    _cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleToFill;
    _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolStyleNone;
    _cycleScrollView.showPageControl = NO ;
    _cycleScrollView.currentPageDotColor = [UIColor grayColor];
    _cycleScrollView.currentPageDotColor = [UIColor whiteColor];
    _cycleScrollView.autoScroll = NO;
    _cycleScrollView.delegate = self;
    _cycleScrollView.infiniteLoop = NO;
    return _cycleScrollView;

}

- (UIButton *)countdownBtn {
    if (_countdownBtn) {
        return _countdownBtn;
    }
    _countdownBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_countdownBtn addTarget:self action:@selector(jionZTabbar) forControlEvents:UIControlEventTouchUpInside];
    [_countdownBtn setBackgroundColor:[UIColor clearColor]];
    [_countdownBtn setTitle:@"进入问答医生" forState:UIControlStateNormal];
    _countdownBtn.layer.borderWidth = 1 ;
    _countdownBtn.layer.borderColor = [KHGreenColor CGColor];
    [_countdownBtn setTitleColor: KHGreenColor forState:UIControlStateNormal];


    _countdownBtn.hidden = YES;
    return _countdownBtn;
}

- (UIImageView *)imageView {
    if (_imageView) {
        return _imageView;
    }
    _imageView = [[UIImageView alloc] init];
//    _imageView.image = [UIImag
    return _imageView;
}

- (UIButton *)timingBtn {
    if (_timingBtn) {
        return _timingBtn;
    }
    _timingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _timingBtn.backgroundColor = KHGaryColor;
    _timingBtn.layer.cornerRadius = 5.0F;
    _timingBtn.layer.masksToBounds = YES;
//    _timingBtn.titleLabel.textColor = [UIColor blueColor];
    [_timingBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_timingBtn addTarget:self action:@selector(timeingButtonAction) forControlEvents:UIControlEventTouchUpInside];
    return _timingBtn;
}
@end
